import { PageModalService } from './../../shared/service/page-modal-service';
// tslint:disable
import { TabsService } from 'src/app/shared/service/tabs.service';
import { Component, OnInit, Input, OnDestroy } from "@angular/core";

import { ActionSheetController, AlertController } from "@ionic/angular";
import { ModalController } from "@ionic/angular";

import { Subscription } from "rxjs";

import { MessageService } from "src/app/shared/service/message.service";

import { isNullOrUndefined } from 'util';

import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { EventService } from 'src/app/shared/service/event.service';
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';

import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";
import { NewBusinessInfoModalComponent } from '../new-business-info-modal/new-business-info-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
import { ShareFormModalComponent } from "../share-form-modal/share-form-modal.component";
import { ImgSlidePage } from "../slides-imgage/img-slide.page";
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ModalFromCenterEnter, ModalFromCenterLeave } from 'src/app/utils/transitions';
declare var $;
@Component({
  selector: 'app-house-transverse-list',
  templateUrl: './house-transverse-list.component.html',
  styleUrls: ['./house-transverse-list.component.scss'],
})
export class HouseTransverseListComponent implements OnInit {
  @Input() tagData: any;
  openInformation = false;
  openRemarks = false;
  icons = [];
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  dataIndex: any;
  firstTextStyle: any = {};
  secondTagStyle: any = {};
  firstTagStyle: any = {};
  secondTestStyle: any = {};
  pageNo: any = 1;
  params: any;
  currentIndex = -1;
  sessionId = localStorage.getItem("sessionId");
  // 声明订阅对象
  subscription: Subscription = null;
  emptyDataHint = "暂无数据";

  selectedIndex = 0;
  selectedId = '';
  selectedStr = '';
  titleCssStyle: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    private message: MessageService,
    private httpService: HttpService,
    private shareService: ShareService,
    public modalController: ModalController,
    public pageModalService: PageModalService
  ) {
    // 清除订阅
    this.eventService.eventEmit.on("clearInformationHallSubscription", (obj) => {
      const reqTag = localStorage.getItem('clearInformationHallSubscriptionTag');
      localStorage.removeItem('clearInformationHallSubscriptionTag');
      if (reqTag !== undefined) {
        try {
          console.log('msg----->clear ... ');
          this.subscription.unsubscribe();
        } catch (error) {
          console.log('error----->' + JSON.stringify(error));
        }
      }
    });
  }

  ngOnInit() {
    const listenerName = this.tagData.name + 'AskForList';
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshDataByEvent(obj);
    });
    this.params = this.tagData.data.submit;

    if (this.tagData && this.tagData.hint) {
      this.emptyDataHint = this.tagData.hint;
    }

    if (!this.subscription && this.tagData.data.submit !== undefined) {
      if (
        this.tagData.data.submit.content &&
        this.tagData.data.submit.content.showName
      ) {
        sessionStorage.setItem(
          "showName",
          this.tagData.data.submit.content.showName
        );
      } else {
        sessionStorage.removeItem("showName");
      }


      this.message.clearMessage();
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {

        if (param === undefined) {
          return;
        } else if (param.type === 'ionRefresh') {
          this.refreshData(param);
          return;
        }
        this.pageNo = 1;
        this.params.sessionId = localStorage.getItem("sessionId");
        // 参数
        this.params.content = param;
        // 页面数据参数
        this.params.content.pageNo = this.pageNo;
        // 请求获取新数据
        this.httpService.post(
          "application/submit",
          this.params,
          res => {
            console.log("submit");
            // 请求数据成功
            if (res.success) {
              const result = res.data.data;
              // 筛选数据
              this.tagData.data.data = result;

              // 自动回到顶部
              setTimeout(() => {
                const el = document.getElementById('information0');
                if (el) {
                  el.scrollIntoView(true);
                }

              }, 200);
            } else {
              // 请求数据失败
              this.appGlobalService.showToast(res.message, 2000, "middle");
            }
          },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, "middle");
          }
        );
      });
    }

    // 1.9.0 改动 新增标题
    if (this.tagData && this.tagData.data !== undefined && this.tagData.data.data && this.tagData.data.data.length > 0) {
      let top = this.tagData.data.data[0];
      if (top !== undefined && top.titleCssStyle) {
        this.titleCssStyle = this.tagData.data.data[0].titleCssStyle;
      }
    }
  }

  /**
   *
   * @param item 打开图标
   */
  openIcon(item, dataIndex?, maxIconList?) {
    if (maxIconList && maxIconList === '2') {
      this.icons = item.slice(1);
    } else {
      this.icons = item.slice(2);
    }

    this.showActionSheet(this.icons);
    // this.openInformation = true;
    this.dataIndex = dataIndex;
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }


  // 分享弹框
  async presentShare58Modal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      backdropDismiss: true,
      component: ShareFormModalComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }


  async presentAlertWithMsgBtn(msg, btnText, button) {
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: btnText,
          handler: () => {
            // this.httpService.changeCallNumber(mobile);
            const params = {
              content: button.submit.content,
              id: button.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                this.appGlobalService.reloadCurrentPage();
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  /**
   *
   * @param item 点击图标
   */
  iconClick(item) {
    const that = this;
    if (item.link) {
      if (item.link.type === 'page') {
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      } else if (item.link.type === 'pageModal') {
        this.pageModalService.openPage(item.link, '', result => {
          if (result) {
            that.updateItem();
          } else {

          }
        });
      }
    }
    if (item.button) {

      if (item.action && item.action === 'question') {
        this.presentAlertWithMsgBtn(item.label, item.text, item.button);
      } else {
        const params = {
          content: item.button.submit.content,
          id: item.button.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          this.appGlobalService.showToast(res.message, 1500, "middle");
          if (res.success) {
            if (item.link && item.link.target) {
              const pageParams = {
                pageId: item.link.target,
                params: item.link.params ? item.link.params : {},
                sessionId: localStorage.getItem("sessionId")
              };
              this.appGlobalService.goToForward(pageParams);
            }
          }
        });
      }


    }
    if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        this.httpService.gotoChat(item);
      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          this.presentShareModal(tmpShareData);
        });
      } else {
        // 修改
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      }
    }
    if (item.modelType === "iconSubmit") {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    }
    if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    }
    if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    }
    if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    }
    if (item.modelType === "remarkList") {
      // tslint:disable-next-line:max-line-length
      // const moreObj = JSON.parse('{"layout":"right","data":[{"submit":{"id":"refresh","content":{"opportunity_id":"5eb3aed42872fb0001f76ed7"}},"action":"submit","label":"刷新","paramName":"opportunity_id"},{"link":{"type":"page","params":{"opportunity_id":"5eb3aed42872fb0001f76ed7"},"target":144348},"action":"link","label":"修改"}],"icon":"nav_icon_more@3x.png"}');
      if (item.listRemark) {
        this.remarkList(item);
      }
    }
    if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    }
    if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        this.remarkList(item);
      }
    }
  }
  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  remarkList(more) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );
  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      const params = {
        pageId: itemObj.link.target,
        params: itemObj.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      // 领取
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
  }
  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          ActionSheetService.close();
          that.iconClick(icons[buttonIndex]);
        }
      }
    );
  }
  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }
  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }
  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }
  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;

    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }
  go(item) {
    this.appGlobalService.openPage(item.link, item.title);
  }

  pullToRefresh() {

  }
  refreshData(event?) {
    this.params.sessionId = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    this.refresh(event, this.params);
  }

  openPage(link) {
    this.pageModalService.openPage(link);
  }

  refreshDataByEvent(param) {
    const tempParam = {
      sessionId: localStorage.getItem("sessionId"),
      params: { search: param.params, eventId: this.tagData.data.footDiv.button.text.eventId },
      pageId: param.target
    }
    // 请求获取新数据
    this.httpService.post("application/page", tempParam, res => {
      // const pageData = res.s
      // 请求数据成功
      if (res.script) {
        let dataArray = [];
        const tags = JSON.parse(res.script).views[0].tags;
        tags.forEach(element => {
          if (element.style === 'counselorChooseListTag') {
            dataArray = element.data.data;
          }
        });

        if (Array.isArray(dataArray) && dataArray.length > 0) {
          this.tagData.data.data = dataArray;

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
      }
    });
  }

  refresh(event, param) {
    // 请求获取新数据
    this.httpService.post("application/submit", param, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;


          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadData(event) {
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);

            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }
      });
    }, 500);
  }

  openModalLink(item, label) {
    try {
      if (label === '业务中' || label === '签约中') {
        if (item && item.type === 'modal') {
          this.openNewBusinessInfoModal("recommend-modal", item);
        }
      } else {
        return;
      }

    } catch (error) {
    }
  }

  async openNewBusinessInfoModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.target,
        params: item.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData.data && tagData.data.length > 0) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: NewBusinessInfoModalComponent,
            componentProps: { tagData }
          });
          await modal.present();
          // 监听销毁的事件
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter

          });
          await modal.present();
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  gotoSharePage(obj) {
    if (obj.tips) {
      this.appGlobalService.showToast(obj.tips, 2000, "middle");
      return;
    }
    if (obj && obj.label) {
      switch (obj.label) {
        case 'qq':
          this.shareService.shareQQ(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'qzone':
          this.shareService.shareQQZone(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'wechat':
          this.shareService.shareWeiXin(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'moment':
          this.shareService.shareMoments(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case '58':
          this.shareService.share58(obj);
          break;
        case 'tikTok': // 抖音
          if (obj.isInValidImgPosterSharing) {
            // 脚本配置 <dataItem name="isInValidImgPosterSharing" value="true"/>
            // 用于新增需求 求租求购，找店、找写字楼、找厂房等：没有图片或信息本身任何图片，生成画报，分享画报图片
            this.shareService.shareDouyinForInValidImg(obj.link.fieldLinkType);
          } else {
            this.shareService.shareDouyin(obj.title, obj.content, obj.imageUrls, obj.webpageUrl, obj.shareType);
          }
          break;
        case 'kwai': // 快手 https://play.google.com/store/apps/details?id=com.kwai.video&hl=zh&gl=US
          this.shareService.shareKuaishou(obj.title, obj.content, obj.imageUrl, obj.webpageUrl, obj.shareType);
          break;
        case 'copy':
          this.shareService.copyUrl(obj.webpageUrl);
          break;
        case 'savePic':
          // this.shareService.savePic();
          break;
        case 'posterSharing':
          this.shareService.posterSharing(obj.link.fieldLinkType);
          break;
        default:
          console.log('...gotoSharePage');
          break;
      }

    }
  }

  openShareModal(obj) {
    if (obj) {
      let subject = obj;
      if (obj.shareBtn && obj.shareBtn.fieldLinkType) {
        subject = obj.shareBtn.fieldLinkType;
      }
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: subject.link.target,
        params: subject.link.params
      };
      this.httpService.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        this.presentShareModal(tmpShareData);
      });
    }
  }

  async previewImage(imageUrl, tmpIndex, isPreview) {
    // event.stopPropagation();
    if (isPreview && isPreview !== undefined) {
      // const that = this;
      let tempImageUrl = 'assets/img/default_img.png';
      if (imageUrl !== undefined) {
        tempImageUrl = imageUrl;
      }
      const value = { img: [tempImageUrl], index: tmpIndex };
      const modal = await this.modalController.create({
        component: ImgSlidePage,
        componentProps: { value: JSON.stringify(value) }
      });
      return await modal.present();
    }

  }


  call(event, phone, name) {
    event.stopPropagation();
    this.presentAlertConfirm(Number(phone), name);
  }
  morebtnClick(moreLink, index) {
    if (!moreLink) {
      return;
    }
    this.dataIndex = index;
    this.showActionSheet(moreLink);
  }
  normalBtnClick(buttonItem, index) {
    if (!buttonItem) {
      return;
    }
    this.dataIndex = index;
    this.iconClick(buttonItem);
  }

  gotoPage(obj) {
    try {
      if (obj) {
        const targetObj = { pageId: obj.target, params: obj.params, sessionId: localStorage.getItem('sessionId') };
        this.appGlobalService.goToForward(targetObj);
      }
    } catch (error) {
    }
  }

  updateItem() {

    const that = this;

    if (!this.tagData.data.data[that.dataIndex].id) {
      return;
    }
    if (that.tagData.data.data[that.dataIndex].updateItemType !== undefined
      && that.tagData.data.data[that.dataIndex].updateItemType === 'delete') {
      that.tagData.data.data.splice(that.dataIndex, 1);
      return;
    }
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {}
    }
    page.params.id = this.tagData.data.data[that.dataIndex].id;
    this.httpService.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'ljManageUserListTag' && element.data && element.data.data[0]) {
          that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
        }

      });
    });
  }

  choiceItem(item, dataIndex) {
    this.selectedIndex = dataIndex;
    this.selectedId = item.id;
    this.selectedStr = item.text;
  }
  saveChoice() {
    this.appGlobalService.goBack();
    this.appGlobalService.popTarget();
    // localStorage.setItem('needRefresh', 'true');
    localStorage.removeItem('needRefresh');
    if (this.tagData.data.footDiv.button.text && this.tagData.data.footDiv.button.text.eventId) {
      if (this.selectedId === '') {
        this.selectedId = this.tagData.data.data[0].id;
        this.selectedStr = this.tagData.data.data[0].text;
      }
      const obj = { id: this.selectedId, text: this.selectedStr }
      this.eventService.eventEmit.emit(this.tagData.data.footDiv.button.text.eventId, obj);
    }
  }

  ngOnDestroy(): void {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
    const listenerName = this.tagData.name + 'AskForList';
    this.eventService.removeCustomListListenersByName(listenerName);
  }

  enlargedView(event, link) {
    event.stopPropagation();
    this.pageModalService.openPage(link);
  }
}


